import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtWidgets import  *
from PyQt6 import uic
import json
import  re

from PyQt6 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(775, 688)
        self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.widget = QtWidgets.QWidget(parent=self.centralwidget)
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.splitter = QtWidgets.QSplitter(parent=self.widget)
        self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.splitter.setObjectName("splitter")
        self.srcContainer = QtWidgets.QTextEdit(parent=self.splitter)
        self.srcContainer.setObjectName("srcContainer")
        self.desContainer = QtWidgets.QTextEdit(parent=self.splitter)
        self.desContainer.setObjectName("desContainer")
        self.horizontalLayout.addWidget(self.splitter)
        self.gridLayout.addWidget(self.widget, 0, 0, 1, 1)
        self.splitter_2 = QtWidgets.QSplitter(parent=self.centralwidget)
        self.splitter_2.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.splitter_2.setObjectName("splitter_2")
        self.clearSrcButton = QtWidgets.QPushButton(parent=self.splitter_2)
        self.clearSrcButton.setObjectName("clearSrcButton")
        self.translateButton = QtWidgets.QPushButton(parent=self.splitter_2)
        self.translateButton.setObjectName("translateButton")
        self.clearDesButton = QtWidgets.QPushButton(parent=self.splitter_2)
        self.clearDesButton.setObjectName("clearDesButton")
        self.gridLayout.addWidget(self.splitter_2, 1, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(parent=MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 775, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(parent=MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.toolBar = QtWidgets.QToolBar(parent=MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.ToolBarArea.TopToolBarArea, self.toolBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.clearSrcButton.setText(_translate("MainWindow", "清除"))
        self.translateButton.setText(_translate("MainWindow", "格式化转换"))
        self.clearDesButton.setText(_translate("MainWindow", "清除"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))




class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 加载 UI 文件
        # uic.loadUi(r'./MainWindow.ui', self)
        # 设置主窗口的固定大小为 UI 中定义的大小
        # self.setFixedSize(self.size())
        self.Widgets_Init()

    def Widgets_Init(self):
        self.srcContainer=self.findChild(QTextEdit,"srcContainer")
        self.desContainer=self.findChild(QTextEdit,"desContainer")

        self.translateButton=self.findChild(QPushButton,"translateButton")
        self.clearSrcButton=self.findChild(QPushButton,"clearSrcButton")
        self.clearDesButton=self.findChild(QPushButton,"clearDesButton")

        self.clearSrcButton.clicked.connect(self.ClearSrcContainer)
        self.clearDesButton.clicked.connect(self.ClearDesContainer)
        self.translateButton.clicked.connect(self.TranslateSrcToDes)
    def ClearSrcContainer(self):
        self.srcContainer.clear()
    def ClearDesContainer(self):
        self.desContainer.clear()
    def TranslateSrcToDes(self):
        srcContent=self.srcContainer.toPlainText()
        desContent=self.process_text(srcContent)
        # desContent=self.format_text_to_json_0(srcContent)
        # if desContent is None:
        #     desContent=self.format_text_to_json_1(srcContent)
        self.ShowResultToDesContainer(desContent)
    def ShowResultToDesContainer(self,desContent):
        self.desContainer.clear()
        self.desContainer.setPlainText(desContent)


    def format_text_to_json_1(self,text):
        try:
            # 将文本内容中的转义字符 \ 处理掉
            # 这里假设传入的 text 是一个 JSON 格式的字符串，但其中包含了额外的转义字符
            clean_text = text.replace(r'\"', '"')

            json_data = json.loads(clean_text)

            return json_data
        except json.JSONDecodeError as e:
            print("解析 JSON 时发生错误:", e)
            return clean_text

    def format_text_to_json_0(self, text):
        try:
            if text.isdigit():
                return text
            clean_text = json.loads(text)
        except Exception:
            return text
        for key, value in clean_text.items():
            try:
                clean_text[key]=self.format_text_to_json_1(value)
            except Exception:
                continue
        # 将解析后的数据重新转换为格式化的 JSON 字符串
        formatted_json = json.dumps(clean_text, indent=4, ensure_ascii=False)

        return formatted_json


    def process_text(self, text):
        res = ''
        if text == '':
            return res
        if text.startswith('{\\') and text.endswith('}'):
            return json.dumps(self.format_text_to_json_1(text),indent=4, ensure_ascii=False)
        # text = text.replace('\n', '')
        if text.startswith('{') and text.endswith('}'):
            if self.IsContainJsonData(text):
                json0 = self.format_text_to_json_0(self.IsContainJsonData(text))
                return json0
        # 使用 splitlines 方法处理换行符
        lines = text.splitlines()
        for line in lines:
            data=self.IsContainJsonData(line)
            if data is not None:
                line=self.format_text_to_json_0(data)

            # line=self.format_text_to_json_0(line)
            if line is not None:
                res += line + '\n'  # 如果需要换行符，可以加上
        return res

    def IsContainJsonData(self,text):
        # 使用正则表达式提取 JSON 部分
        json_match = re.search(r'\{.*\}', text, re.DOTALL)

        if not json_match:
            return None
        json_str = json_match.group()
        return json_str


if __name__ == '__main__':
    app = QApplication([])
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec())
